package com.leiy.test.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;

public class HttpClientPool {

    @Test
    public void testPool(){
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

        // 池子最大连接数量
        cm.setMaxTotal(100);
        // 每台服务器的最大连接数
        cm.setDefaultMaxPerRoute(10);
        doGet(cm);
        doGet(cm);
    }

    private void doGet(PoolingHttpClientConnectionManager cm) {
        HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(cm);
        CloseableHttpClient httpClient = httpClientBuilder.build();

        HttpGet httpGet = new HttpGet("https://ke.qq.com");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            // httpClient 不可以再关闭了
        }
    }
}
